﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Design;
using DnPakExplorer.Forms;

namespace DnPakExplorer.Controls {
	public partial class RichText : UserControl {

		InfoOverlayForm.RichTextDrawBlock mRichText;

		public RichText() {
			InitializeComponent();
		}

		[Editor("System.ComponentModel.Design.MultilineStringEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
		[SettingsBindable(true)]
		[Browsable(true)]
		public override string Text {
			get {
				return base.Text;
			}
			set {
				base.Text = value;
				StringFormat sf = new StringFormat();
				if (AutoSize) {
					Rectangle rect = new Rectangle(new Point(0, 0), MaximumSize);
					if (rect.Width <= 0)
						rect.Width = int.MaxValue;
					if (rect.Height <= 0) {
						rect.Height = int.MaxValue;
					}
					if (rect.Width < MinimumSize.Width && MinimumSize.Width > 0)
						rect.Width = MinimumSize.Width;
					if (rect.Height < MinimumSize.Height && MinimumSize.Height > 0)
						rect.Height = MinimumSize.Height;
					List<InfoOverlayForm.RichTextDrawBlock.RichString> richStrings;
					mRichText = new InfoOverlayForm.RichTextDrawBlock(richStrings = InfoOverlayForm.RichTextDrawBlock.Measure(
					InfoOverlayForm.RichTextDrawBlock.Parse(value, Font, ForeColor),
					this.CreateGraphics(), sf, rect));
					Rectangle bounds = new Rectangle();
					foreach(InfoOverlayForm.RichTextDrawBlock.RichString rs in richStrings){
						if (rs.rect.Right > bounds.Width) {
							bounds.Width = (int)rs.rect.Right;
						}
						if (rs.rect.Bottom > bounds.Height) {
							bounds.Height = (int)rs.rect.Bottom;
						}
					}
					ClientSize = bounds.Size;
					Refresh();
				} else {
					mRichText = new InfoOverlayForm.RichTextDrawBlock(InfoOverlayForm.RichTextDrawBlock.Measure(
					InfoOverlayForm.RichTextDrawBlock.Parse(value, Font, ForeColor),
					this.CreateGraphics(), sf, ClientRectangle));
					Refresh();
				}
			}
		}

		private void RichText_Paint(object sender, PaintEventArgs e) {
			if(mRichText != null)
				mRichText.Draw(e.Graphics);
		}

		private void RichText_SizeChanged(object sender, EventArgs e) {
			if(!AutoSize)
				Text = Text;
			Invalidate();
		}


	}
}
